package tardistv.view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import tardistv.controller.Controller;
import tardistv.model.Show;

/**
 * @author Tardis TV Team
 */
public class SubscribeDialog extends JDialog {

    private JLabel lbSelectShows;
    private JScrollPane scrollPane;
    private JButton btSubscribe;
    private JList listShows;
    private ArrayList<Show> shows;

    public SubscribeDialog(MainWindow frame, ArrayList<Show> shows) {
        this.shows = shows;
        setTitle("Subscribe to TV Shows");
        setLocationRelativeTo(frame);
        setModal(true);
        setSize(300, 300);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(getLbSelectShows(), BorderLayout.NORTH);
        getContentPane().add(getScrollPane(), BorderLayout.CENTER);
        getContentPane().add(getBtSubscribe(), BorderLayout.SOUTH);
        setVisible(true);
    }

    private JLabel getLbSelectShows() {
        if (lbSelectShows == null) {
            lbSelectShows = new JLabel("Select the shows you want to subscribe to");
        }
        return lbSelectShows;
    }

    private JButton getBtSubscribe() {
        if (btSubscribe == null) {
            btSubscribe = new JButton("Subscribe");
            btSubscribe.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    subscribeToSelectedShows();
                }
            });
        }
        return btSubscribe;
    }

    private JList getListShows() {
        if (listShows == null) {
            listShows = new JList(shows.toArray());
            listShows.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        }
        return listShows;
    }

    private JScrollPane getScrollPane() {
        if (scrollPane == null) {
            scrollPane = new JScrollPane(getListShows());
        }
        return scrollPane;
    }

    private void subscribeToSelectedShows(){
        for(Object object : listShows.getSelectedValues())
            Controller.getInstance().addSubscriptionToShow((Show)object);
        this.dispose();
    }
}
